<?php

namespace app\api\hook;


use think\Db;
use think\Env;
use think\Exception;

class Retail
{
    //一级分销比例
    private $first;
    //二级分销比例
    private $second;

    public function __construct()
    {
        $this->student_first = Env::get('distribution.first', '20') / 100;
        $this->student_second = Env::get('distribution.second', '10') / 100;
    }

    // 学生注册分销逻辑
    function calculatePoint($data)
    {
        if (!Env::get('distribution.student_register')) {
            return false;
        }
        $by_invite_code = $data['by_invite_code'];
        $student_id = $data['student_id'];
        //注册基础积分
        $student_register_num = Env::get('distribution.student_register_num');
        $first_num = floor($student_register_num * $this->first);
        $second_num = floor($student_register_num * $this->second);
        Db::startTrans();
        $uid = Db::name('student')->where('invite_code', $by_invite_code)->field('id,user_name')->find();
        if (!empty($uid['id'])) {
            //创建关联关系
            $invest = [
                'role' => "student",
                'uid' => $uid['id'],
                'to_role' => "student",
                'to_uid' => $student_id,
            ];
//            $invest_id = $this->createTeacherInvest($invest);
            $invest_id = Db::name('invest')->insert($invest, false, true);
            //为邀请人存入积分
            if (Env::get('distribution.by_student_register_fixed')) {
                //走固定积分
                $fix_num = Env::get('distribution.by_student_register_fixed_num');
                Db::name('student')->where('id', $uid['id'])->setInc('point', $fix_num);
                //存记录
                $this->storeLog($invest_id,$fix_num);
            } else {
                //走倍率
                $incData = [
                    [
                        'id' => $uid['id'],
                        'point' => $first_num,
                        'invest_id' =>$invest_id
                    ],
                    [
                        'id' => $this->investPersonID($uid['id']),
                        'point' => $second_num,
                        'invest_id' =>$invest_id
                    ]
                ];
                $this->incPoint($incData);
            }
            Db::commit();
            return true;
        } else {
            Db::rollback();
            return false;
        }
    }

    /**
     * Notes:公共分销
     * User: XingLiangRen
     * Date: 2020/9/2
     * Time: 14:04
     * @data orderID[订单id]
     */
    public function commonDistribution($data)
    {
        //1.根据订单编号计算出一二级收益用户
        $orderData = Db::name('order')->where(['id'=>$data['orderID']])->field('userId,amount')->find();
        $userId = $orderData['userId'];
        $firstID = Db::name('invest')->where(['to_role' => 'student', 'to_uid' => $userId])->find();
        //2.拿到1、2级的分销比例 类内属性中有
        //3.计算1、2级的应得收益
        $firstPrice = $orderData['amount'] * $this->first;
        $secondPrice = $orderData['amount'] * $this->second;
        //4.为相应用户增加收益并进行记录
        if(!empty($firstID)){
            $secondID = Db::name('invest')->where(['role' => $firstID['role'], 'uid' => $firstID['uid']])->find();
            Db::name($this->getTableName($firstID['role']))->where('id',$firstID['uid'])->setInc('sale_money',$firstPrice);
            $this->storeLog($firstID['id'],$firstPrice,$data['orderID'],2);
            if(!empty($secondID)){
                Db::name($this->getTableName($secondID['role']))->where('id',$secondID['uid'])->setInc('sale_money',$secondPrice);
                $this->storeLog($secondID['id'],$secondPrice,$data['orderID'],2);
            }
        }
        return true;
    }

    /**
     * Notes:通用推荐关系
     * User: XingLiangRen
     * Date: 2020/9/2
     * Time: 14:30
     * @param $data role 推荐人类型[teacher|help|partner] uid 推荐人id invite_code 邀请码
     */
    public function createTeacherInvest($data){
        $toUser = $this->getToUser($data['invite_code']);
        $user= Db::name($this->getTableName($data['role']))->where('id',$data['uid'])->find();
        if($toUser === false){
            return  '无效的邀请码';
        }
        //创建关联关系
        $invest = [
            'to_role'          => $data['role'],
            'to_uid'           => $data['uid'],
            'to_nick_name'     => $user['nick_name'],
            'role'             => $toUser['role'],
            'uid'              => $toUser['uid'],
        ];
        // 添加站内消息
        $phone = Db::name($this->getTableName($data['role']))->where('id',$data['uid'])->field('phone')->find()['phone'];
        $phone = substr_replace($phone, '****', 3, 4);
        $notice = [
            'form_id'      => 0,
            'form_role'    => 0,
            'to_id'        => $toUser['uid'],
            'to_role'      => $toUser['role'],
            'created_time' => date('Y-m-d H:i:s'),
            'content'      => $phone . "用户根据你的邀请码注册了账号",
            'title'        => $phone . "用户根据你的邀请码注册了账号"
        ];
        Db::name('notices')->insert($notice);
       return Db::name('invest')->insert($invest, false, true);
    }

    /**
     * Notes:根据邀请码获取上级的信息
     * User: XingLiangRen
     * Date: 2020/9/2
     * Time: 16:41
     * @param $invite_code
     */
    private function getToUser($invite_code){
        $tables = ['teacher','helper','partner'];
        foreach ($tables as $v){
            $res = Db::name($v)->where('invite_code',$invite_code)->find();
            if(!empty($res)){
                return ['role' => $v , 'uid' => $res['id']];
            }
        }
        return false;
    }

    private function incPoint($data)
    {
        foreach ($data as $v) {
            Db::name('student')->where('id', $v['id'])->setInc('point', $v['point']);
            $this->storeLog($v['invest_id'],$v['point']);
        }
    }

    private function getTableName($str){
        $returnStr = '';
        switch ($str){
            case 'teacher' : $returnStr = 'teacher'; break;
            case 'help' : $returnStr = 'helper'; break;
            case 'partner' : $returnStr = 'partner'; break;
            case 'student' : $returnStr = 'student'; break;
        }
        return $returnStr;
    }
    private function storeLog($invest_id,$ponit,$order_id = 0, $type = 1){
        $invite_earnings = [
            'invest_id' => $invest_id,
            'earnings' => $ponit,
            'create_time' => date("Y-m-d H:i:s"),
            'order_id' => $order_id,
            'type' => $type
        ];
        Db::name('invest_earnings')->insert($invite_earnings);
    }
    private function investPersonID($uid)
    {
        $data = Db::name('invest')->where('to_uid', $uid)->find();
        if (!empty($data) && $data['role'] == "student") {
            return $data ? 0 : $data['uid'];
        } else {
            return 0;
        }
    }

    function run($data)
    {
        return $data;
    }
}